package com.shinewind.sso.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shinewind.sso.entity.MyUser;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class MyAdminJwtAuthFilter extends AbstractAuthenticationProcessingFilter {
    public MyAdminJwtAuthFilter(AuthenticationManager authenticationManager) {
        super(new AntPathRequestMatcher("/sso/admin/model/sign","POST"));
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse resp) throws AuthenticationException, IOException, ServletException {
        MyUser user = new ObjectMapper().readValue(req.getInputStream(),MyUser.class);
        System.out.println("user:"+user);
        //校验
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        auth.setDetails(user);
        return getAuthenticationManager().authenticate(auth);
    }
}
